<?php

declare (strict_types=1);

namespace magein\think\pay;

use magein\pay\extension\PayQrcodeOrderInterface;
use magein\pay\PayConfig;
use magein\think\pay\model\PayQrcodeModel;

class PayQrcode implements PayQrcodeOrderInterface
{

    /**
     * @param array $data
     * @return string
     */
    public function create(array $data): string
    {
        $qrcode = new PayQrcodeModel();

        $i = 0;
        $pay_no = '';
        while (true) {
            if ($i > 50) {
                break;
            }
            $pay_no = date('YmdHi') . rand(1000000, 99999999);
            $pay_no = substr($pay_no, 0, 18);
            $record = PayQrcodeModel::_payNo($pay_no);
            if (empty($record)) {
                break;
            }
            $i++;
        }

        if (empty($pay_no)) {
            return '';
        }

        $expire_in = PayConfig::qrcode('expire_in') ?: 600;
        if ($expire_in <= 60) {
            $expire_in = 600;
        }

        $qrcode->pay_no = $pay_no;
        $qrcode->expire_in = date('Y-m-d H:i:s', time() + $expire_in);
        $qrcode->available = 1;
        $qrcode->params = $data;
        $qrcode->save();

        return $qrcode->id ? $pay_no : '';
    }

    /**
     * @param $pay_no
     * @return array
     */
    public function getByPayNo($pay_no): array
    {
        if (empty($pay_no)) {
            return [];
        }

        $record = PayQrcodeModel::_payNo($pay_no);

        return $record ? $record->toArray() : [];
    }

    public function available($data): bool
    {
        if (!is_array($data)) {
            $data = $this->getByPayNo($data);
        }

        $expire_in = $data['expire_in'] ?? '';

        if (empty($expire_in)) {
            return false;
        }

        $expire_in = strtotime($expire_in);
        if ($expire_in < time()) {
            return false;
        }

        $available = $data['available'] ?? 0;
        if ($available != 1) {
            return false;
        }

        return true;
    }

    /**
     * @param $pay_no
     * @return mixed
     */
    public function unavailable($pay_no)
    {
        return PayQrcodeModel::where('pay_no', $pay_no)->save([
            'available' => 0
        ]);
    }

    /**
     * 获取支付二维码的保存地址
     * @param $save_path
     * @return string
     */
    public function getTempSavePath($save_path): string
    {
        $save_path = str_replace(public_path(), '', $save_path);

        $domain = PayConfig::domain();

        return sprintf('%s/%s', $domain, $save_path);
    }
}